package com.lzp.leetcode.ext

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 4/26/21
 */
data class Node(var next: Node?, val value: Int) {
    override fun toString(): String {
        return "$value " + if (next != null) ", ${next.toString()}" else ""
    }
}

class Queue(var node:Node,var next: Node?){

}


class BlockQueue {

    @Volatile
    private var isBlock = false

    var node: Node? = null

    var isFirst = true//防止无限打印log

    fun setBlock(block: Boolean) {
        this.isBlock = block
    }

    @Synchronized
    fun getNext(): Node? {
        while (isBlock) {
            //阻塞掉
            if (isFirst) {
                println("阻塞中")
                isFirst = false
            }
        }
        val next = node?.next
        node = next
        return next
    }

    override fun toString(): String {
        return node.toString()
    }
}

fun main() {
    val queue = BlockQueue()

    val node3 = Node(null, 3)
    val node2 = Node(node3, 2)
    val node1 = Node(node2, 1)
    val node0 = Node(node1, 0)
    queue.node = node0
    println("原始队列：${queue.toString()}")
    doBlock(queue)
}

fun doBlock(queue: BlockQueue) {
    Thread(Runnable {
        Thread.sleep(2000)
        queue.setBlock(false)
    }).start()

    var node = queue.node
    while (node != null) {
        println(node.value.toString())
        if (node.value == 1) {
            //阻塞
            queue.setBlock(true)
        }
        node = queue.getNext()
    }
}
